﻿using System.Globalization;
using System.IO.Compression;
using System.Web;
using System.Web.Mvc;

namespace FlickrXplorer.Web
{
    public class CompressResponseAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuting (ActionExecutingContext filterContext)
        {
            HttpContextBase context = filterContext.HttpContext;

            if (context != null && context.Request != null)
            {
                string acceptEncoding = context.Request.Headers["Accept-Encoding"];

                if (!string.IsNullOrEmpty(acceptEncoding))
                {
                    acceptEncoding = acceptEncoding.ToLower(CultureInfo.InvariantCulture);
                }

                if (acceptEncoding != null && acceptEncoding.Contains("gzip"))
                {
                    context.Response.AppendHeader("Content-encoding", "gzip");
                    context.Response.Filter = new GZipStream(context.Response.Filter, CompressionMode.Compress);
                }
            }
        }
    }
}